<template>
  <el-dialog v-model="visible" title="拍照" width="800" :append-to-body="true" @close="close">

    <video id="video" width="800" height="600" v-show="videoState"></video>

    <canvas id="canvas" width="800" height="600" style="display: none">
    </canvas>
    <div class="flex flex-wrap py-4">
      <div class="relative flex justify-center items-center mr-2 mb-2" v-for="(item, index) in file_url" :key="index">
        <el-image style="width: 80px; height: 60px;" :src="item" :preview-src-list="file_url"></el-image>
        <svg-icon class="absolute -right-1.5 -top-1.5 text-white z-10" icon-class="state_fail_cover"
          @click="deleteImage(index)"></svg-icon>
      </div>
    </div>
    <!-- </div> -->
    <template #footer>
      <div class="flex justify-center py-2">
        <el-button class="mr-2" type="primary" @click="takePhone">拍照</el-button>
        <!-- <el-button type="primary" @click="rephotograph">重拍</el-button> -->
        <el-button type="primary" @click="cofirm">上传</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="DialogImage">
import { reactive, ref, toRefs } from 'vue'
import VUpload from '@/components/VUpload/index.vue'
import { uploadSaveImage } from '@/api/public';
import { ElMessage } from 'element-plus';
import { uploadImg } from './api'

const visible = ref(false)
const blobFile = ref(null)
const canvas = ref(null)
const video = ref(null)
const videoState = ref(false)
const mediaStreamTrack = ref()

const data = reactive({
  type: '',
  detail_id: '',
  file_url: [],
  blobFile: null,
  canvas: null,
  video: null,
  videoState: null,
  mediaStreamTrack: null
})

const { detail_id, type, file_url } = toRefs(data)

const open = (openType, opennId) => {
  type.value = openType
  detail_id.value = opennId
  visible.value = true
  videoState.value = true
}

const rephotograph = () => {
  videoState.value = true
  file_url.value = ''
}

const emit = defineEmits(['success'])


const cofirm = async () => {
  try {
    const res = await uploadSaveImage({
      file_url_arr: file_url.value,
      type: type.value,
      detail_id: detail_id.value,
    })
    ElMessage.success('上传成功')
    emit('success', file_url.value)
    close()
  } catch (e) {
    throw Error(e)
  }
}


onMounted(() => {
  // 摄像头
  video.value = document.getElementById('video')
  //画布
  canvas.value = document.getElementById('canvas')
  console.log(canvas.value)
})

watch(videoState, (newValue, oldValue) => {
  if (newValue) {
    let video = document.querySelector('video')

    // 兼容代码
    window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL
    if (navigator.mediaDevices === undefined) {
      navigator.mediaDevices = {}
    }
    if (navigator.mediaDevices.getUserMedia === undefined) {
      navigator.mediaDevices.getUserMedia = function (constraints) {
        var getUserMedia =
          navigator.webkitGetUserMedia ||
          navigator.mozGetUserMedia ||
          navigator.msGetUserMedia
        if (!getUserMedia) {
          return Promise.reject(
            new Error('getUserMedia is not implemented in this browser')
          )
        }
        return new Promise(function (resolve, reject) {
          getUserMedia.call(navigator, constraints, resolve, reject)
        })
      }
    }

    let mediaOpts = {
      audio: false,
      video: true,
      video: { facingMode: 'user' }, // 或者 "environment"
      // video: { width: 1280, height: 720 }
      // video: { facingMode: { exact: "environment" } }// 或者 "user"
    }
    navigator.mediaDevices
      .getUserMedia(mediaOpts)
      .then(function (stream) {
        mediaStreamTrack.value = stream
        video = document.querySelector('video')
        if ('srcObject' in video) {
          video.srcObject = stream
        } else {
          video.src =
            (window.URL && window.URL.createObjectURL(stream)) || stream
        }
        video.play()
      })
      .catch(function (err) {
        console.log(err)
      })
  }
})


// base64转file方式附上
const dataURLtoFile = (dataurl, filename) => {
  var arr = dataurl.split(',')
  var mime = arr[0].match(/:(.*?);/)[1]
  var bstr = atob(arr[1])
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, { type: mime })
}


const takePhone = () => {
  // console.log(document.getElementById('canvas'))
  // console.log(video.value)
  const canvas = document.getElementById('canvas')
  const video = document.getElementById('video')

  //点击拍照截图画面
  canvas.getContext('2d').drawImage(video, 0, 0, 800, 600)
  let dataurl = canvas.toDataURL('image/jpeg')
  blobFile.value = dataURLtoFile(dataurl, 'camera.jpg') // 储存响应的图片File
  // tips 此时已经获取到了File类型的数据 可直接向后端传递数据
  // 若需要formData类型的数据,需加上以下代码

  // 创建虚拟表单保存file
  let formData = new FormData()
  formData.append('file', blobFile.value) //图片内容
  // tips 此时已经获取到了fromData类型的数据
  // console.log(formData.getAll('file'), 123) // 查看数据内容
  uploadImg(formData).then(res => {
    file_url.value.push(res.data['data-show-file'])
  })

  // 剩下就是html处理
  // videoState.value = false // 关闭video
  canvas.getContext('2d').clearRect(0, 0, 800, 600) //清除画布
  // 关闭摄像头

}

const deleteImage = (index) => {
  file_url.value.splice(index, 1)
}

const close = () => {
  file_url.value = []
  videoState.value = false // 关闭video
  mediaStreamTrack.value.getVideoTracks().forEach(function (track) {
    track.stop()
  })
  visible.value = false
}
defineExpose({ open })
</script>
<style lang="scss" scoped>
.p {
  position: relative;
}
</style>